import ReceiptActive from '@/pages/cues/active/components/ReceiptActive';
import { activeAnalysis } from '@/services/api/api-cues-active';
import { pageCuesSeekActive } from '@/services/api/api-cues-seek';
import { searchTreeOrganization } from '@/services/api/api-cues-submit';
import { FileImageOutlined, PaperClipOutlined } from '@ant-design/icons';
import {
  LightFilter,
  ProColumns,
  ProFormCascader,
  ProFormDateRangePicker
} from '@ant-design/pro-components';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Cascader, Input, Space, Tag } from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import DetailsClue from '../../clue/components/DetailsClue';

import './TableActive.less';
import style from './TableActive.less';

const TableActive: React.FC = () => {
  const access = useAccess();

  const [width, setWidth] = useState(500);

  const actionRef = useRef<ActionType>();

  const [articleOrganizations, setArticleOrganizationState] = useState<any[]>([]);

  const [showList, setShowListState] = useState(false);

  /**
   * 加载 单位 列表
   * @param key
   */
  const treeOrganizationData = async () => {
    try {
      const response = await searchTreeOrganization();
      if (response.code === 0) {
        setArticleOrganizationState(response.data);
      }
    } catch (error) {}
  };

  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});
  const [loading, setLoadingState] = useState(true);
  const [responsive, setResponsive] = useState(false);
  const [totalData, setTotalDataState] = useState<CuesActiveData.Analysis>();
  useEffect(() => {
    treeOrganizationData();
    analysisData();
  }, []);
  /**
   * 加载 单位 列表
   * @param key
   */
  const analysisData = async () => {
    try {
      const response = await activeAnalysis();
      if (response.code === 0) {
        console.log(response.data);
        setLoadingState(false);
        setTotalDataState(response.data);
      }
    } catch (error) {}
  };

  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const columns: ProColumns<CuesActiveData.ActivePage>[] = [
    {
      title: '报送线索',
      dataIndex: 'articleName',
      // copyable: true,
      search: false,
      ellipsis: true,
      width: '300px',
      align: 'center',
      key: 'articleName',
      render: (dom, record, _index, action) => {
        return (
          <div
            style={{
              textAlign: 'left',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
            }}
          >
            {record.isImage === 1 ? <FileImageOutlined /> : <></>}
            {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
            <DetailsClue
              id={record.id}
              name={record.articleName}
              onRefurbish={() => {
                actionRef?.current?.reload();
              }}
              submitId={''}
            />
          </div>
        );
      },
    },
    {
      title: '单位',
      key: 'articleOrganizationAvatar',
      dataIndex: 'articleOrganizationAvatar',
      width: '180px',
      align: 'center',
      search: false,
      valueType: 'avatar',
      render: (dom, row) => (
        <div
          style={{
            textAlign: 'left',
            marginLeft: '24px',
          }}
        >
          {/* <Tag color={findTagColor(row.articleOrganizationTopName)}>
            {row.articleOrganizationTopName}
          </Tag> */}
          <span>{dom}</span>
          {row.articleOrganizationName}
        </div>
      ),
    },
    {
      title: '线索方向',
      dataIndex: 'articleIndustryName',
      key: 'articleIndustryName',
      width: '80px',
      align: 'center',
      search: false,
      render: (_, row) => {
        let industrys = row?.articleIndustrys;

        if (industrys.length > 2) {
          industrys = industrys.slice(0, 2);
          industrys.push({
            label: '...',
            value: '...',
          });
        }

        return (
          <Space size={[0, 8]} wrap>
            {industrys?.map(
              (item) =>
                // <Tag key={item.value}>{item.label}</Tag>
                item.label,
            )}
          </Space>
        );
      },
    },
    {
      title: '标签',
      dataIndex: 'articleLabels',
      key: 'articleLabels',
      width: '200px',
      align: 'center',
      search: false,
      render: (_, row) => {
        let labels = row?.articleLabels;

        if (labels.length > 2) {
          labels = labels.slice(0, 2);
          labels.push({
            label: '...',
            value: '...',
          });
        }
        return (
          <Space size={[0, 8]} wrap>
            {labels?.map((item) => (
              <Tag key={item.value}>{item.label}</Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '新闻联络人',
      dataIndex: 'articleAccountName',
      // copyable: true,
      ellipsis: true,
      search: false,
      width: '100px',
      align: 'center',
      key: 'articleAccountName',
    },
    // {
    //   title: '阅读情况',
    //   hideInSearch: true,
    //   hideInTable: !access.线索征集x配置x管理员,
    //   dataIndex: 'receipt',
    //   key: 'receipt',
    //   valueType: 'avatar',
    //   width: '80px',
    //   align: 'center',
    //   search: false,
    //   render: (dom, record) => {
    //     return <ReceiptActive id={record.id} receipt={record.receipt} />;
    //   },
    // },
    {
      title: '阅读情况',
      hideInSearch: true,
      hideInTable: !access.线索征集x配置x管理员,
      dataIndex: 'receipt',
      key: 'receipt',
      valueType: 'avatar',
      width: '80px',
      align: 'center',
      search: false,
      render: (dom, record) => {
        return <ReceiptActive id={record.id} receipt={record.readCount} />;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: '120px',
      align: 'center',
      search: false,
    },
    {
      title: '报送日期',
      dataIndex: 'createdTimes',
      key: 'createdTimes',
      valueType: 'dateRange',
      hideInTable: true,
    },
  ];

  return (
    <ProTable<CuesActiveData.ActivePage>
      columns={columns}
      actionRef={actionRef}
      request={async (params = {}) => {
        if (params.organizationIds) {
          const organizationParentIds: string[] = [];
          let organizationIds: string[] = [];

          params.organizationIds.forEach((item: string | any[]) => {
            if (item.length === 1) {
              organizationParentIds.push(item[0]);
            } else if (item.length > 1) {
              organizationIds.push(item[1]);
            }
          });
          organizationParentIds.forEach((id) => {
            const ids = articleOrganizations.find((item) => item.id === id).children;
            organizationIds = organizationIds.concat(ids.map((item: any) => item.id));
          });
          params.articleOrganizationIds = organizationIds;
        }

        const response = await pageCuesSeekActive({
          createdSource: 1,
          ...queryParam,
          ...params,
        });

        return Promise.resolve({
          data: response.data.data,
          total: response.data.total,
          success: response.code === 0,
        });
      }}
      rowKey="id"
      dateFormatter="string"
      bordered
      search={false}
      sticky
      ghost
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 20,
      }}
      headerTitle={
        <div
          style={{
            display: 'flex',
          }}
        >
          <Input.Search
            placeholder="查询标题"
            enterButton="搜索"
            allowClear
            style={{ maxWidth: 250, width: '100%' }}
            onChange={(e) => {
              setQueryParamState({ ...queryParam, articleName: e.target.value });
            }}
            onSearch={(value) => {
              actionRef.current?.reset();
            }}
          />
          {/* <ProFormCascader
            hidden={access.线索征集x配置x提供者 || access.线索征集x配置x区县提供者}
            width="xl"
            className={style.assignStyle}
            name="assignOrganizationIds"
            placeholder="选择单位"
            style={{
              padding: '10px',
            }}
            formItemProps={{
              style: {
                width: width - 800,
                marginLeft: '18px',
                marginBottom: '0px',
              },
            }}
            fieldProps={{
              options: articleOrganizations,
              showSearch: { filter },
              multiple: true,
              removeIcon: true,
              allowClear: true,
              maxTagCount: 'responsive',
              showCheckedStrategy: Cascader.SHOW_CHILD,
              // popupMatchSelectWidth: 400,
              // dropdownStyle: { height: 400, width: 400 , overflow: 'auto'},
              onChange(value, selectOptions) {
                setQueryParamState({ ...queryParam, articleOrganizationIds: value });
                actionRef.current?.reset();
              },
            }}
          /> */}
        </div>
      }
      toolbar={{
        style: {
          marginTop: '-16px',
        },
        filter: (
          <LightFilter
            onValuesChange={(value) => {
              setQueryParamState(value);
              actionRef?.current?.reset();
            }}
          >
            <ProFormDateRangePicker
              name="createdTimes"
              label="创建日期"
              allowClear
              fieldProps={{
                allowClear: true,
                placeholder: ['开始日期', '结束日期'],
                format: 'YYYY-MM-DD',
                ranges: {
                  今日: [dayjs(), dayjs()],
                  本月: [dayjs().startOf('month'), dayjs().endOf('month')],
                  上月: [
                    dayjs().startOf('month').subtract(1, 'months'),
                    dayjs().endOf('month').subtract(1, 'months'),
                  ],
                  最近7天: [dayjs().subtract(6, 'days'), dayjs()],
                  最近60天: [dayjs().subtract(59, 'days'), dayjs()],
                  最近90天: [dayjs().subtract(89, 'days'), dayjs()],
                },
              }}
            />
          </LightFilter>
        ),
      }}
    />
  );
};
export default TableActive;
